import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../widgets/mystical_backdrop_canvas.dart';
import '../widgets/ethereal_tab_switcher.dart';
import '../widgets/enchanted_form_vessel.dart';
import '../widgets/whispering_input_field.dart';
import '../widgets/crimson_action_orb.dart';
import '../widgets/shadow_realm_apple_portal.dart';
import '../widgets/ancient_terms_whisper.dart';

class MysticalAuthSanctuary extends StatefulWidget {
  const MysticalAuthSanctuary({super.key});

  @override
  State<MysticalAuthSanctuary> createState() => _MysticalAuthSanctuaryState();
}

class _MysticalAuthSanctuaryState extends State<MysticalAuthSanctuary> {
  bool _isLoginMode = true;
  bool _isLoading = false;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  void _toggleMode() {
    setState(() {
      _isLoginMode = !_isLoginMode;
    });
  }

  Future<void> _handleSubmit() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 2));

    if (mounted) {
      setState(() {
        _isLoading = false;
      });

      // 这里添加实际的登录/注册逻辑
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(_isLoginMode ? '登录成功！' : '注册成功！'),
          backgroundColor: const Color(0xFFD2691E),
        ),
      );
    }
  }

  void _handleAppleSignIn() {
    // 处理Apple登录
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Apple登录功能开发中...'),
        backgroundColor: Colors.black,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景
          const MysticalBackdropCanvas(),

          // 返回按钮
          Positioned(
            top: MediaQuery.of(context).padding.top + 16.h,
            left: 16.w,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white.withValues(alpha: 0.2),
                shape: BoxShape.circle,
              ),
              child: IconButton(
                onPressed: () => Navigator.of(context).pop(),
                icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white),
              ),
            ),
          ),

          // 主要内容
          SafeArea(
            child: Column(
              children: [
                SizedBox(height: 60.h),

                // 标签切换器
                EtherealTabSwitcher(
                  isLoginMode: _isLoginMode,
                  onToggle: _toggleMode,
                ),

                // 表单容器
                Expanded(
                  child: SingleChildScrollView(
                    child: EnchantedFormVessel(child: _buildFormContent()),
                  ),
                ),

                SizedBox(height: 20.h),

                // Apple登录按钮
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 40.w),
                  child: ShadowRealmApplePortal(onPressed: _handleAppleSignIn),
                ),

                SizedBox(height: 20.h),

                // 条款链接
                const AncientTermsWhisper(),

                SizedBox(height: 30.h),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFormContent() {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          SizedBox(height: 20.h),

          // 用户名/账户名输入框
          WhisperingInputField(
            labelText: _isLoginMode ? 'Username' : 'Enter your account name',
            hintText:
                _isLoginMode
                    ? 'Enter your username'
                    : 'Enter your account name',
            controller: _usernameController,
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return _isLoginMode
                    ? 'Please enter username'
                    : 'Please enter account name';
              }
              return null;
            },
          ),

          SizedBox(height: 24.h),

          // 密码输入框
          WhisperingInputField(
            labelText: 'Password',
            hintText: 'Enter your password',
            isPassword: true,
            controller: _passwordController,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter password';
              }
              if (value.length < 6) {
                return 'Password must be at least 6 characters';
              }
              return null;
            },
          ),

          // 注册模式下的确认密码
          if (!_isLoginMode) ...[
            SizedBox(height: 24.h),
            WhisperingInputField(
              labelText: 'Re-confirm your password',
              hintText: 'Re-confirm your password',
              isPassword: true,
              controller: _confirmPasswordController,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please confirm your password';
                }
                if (value != _passwordController.text) {
                  return 'Passwords do not match';
                }
                return null;
              },
            ),
          ],

          SizedBox(height: 40.h),

          // 提交按钮
          CrimsonActionOrb(
            text: _isLoginMode ? 'Log In' : 'Sign Up',
            onPressed: _handleSubmit,
            isLoading: _isLoading,
          ),

          SizedBox(height: 20.h),
        ],
      ),
    );
  }
}
